package com.mallcloud.mall.mall.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mallcloud.mall.common.core.constant.enums.mall.PointsCouponEnum;
import com.mallcloud.mall.common.core.exception.FailException;
import com.mallcloud.mall.mall.api.entity.XglQRCodePaymentCouponViewModel;
import com.mallcloud.mall.mall.mapper.XglQRCodePaymentCouponViewMapper;
import com.mallcloud.mall.mall.service.XglQRCodePaymentCouponViewService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *  星光里二维码支付牌-电子券|手工券
 */
@Slf4j
@Service
@AllArgsConstructor
public class XglQRCodePaymentCouponViewServiceImpl extends ServiceImpl<XglQRCodePaymentCouponViewMapper, XglQRCodePaymentCouponViewModel> implements XglQRCodePaymentCouponViewService {

	@Override
	public List<XglQRCodePaymentCouponViewModel> listQRCodePaymentCoupon(XglQRCodePaymentCouponViewModel dto) {
		// 可用券 ： 券开始日期 >= now >= 券结束日期
		Date now = new Date();
		return this.list(new LambdaQueryWrapper<XglQRCodePaymentCouponViewModel>()
				.eq(StrUtil.isNotBlank(dto.getUserPhone()), XglQRCodePaymentCouponViewModel::getUserPhone, dto.getUserPhone())
				.eq(XglQRCodePaymentCouponViewModel::getStatus, PointsCouponEnum.StatusEnum.Y.name())
				.le(XglQRCodePaymentCouponViewModel::getStartDate, now)
				.ge(XglQRCodePaymentCouponViewModel::getEndDate, now)
				.orderByDesc(XglQRCodePaymentCouponViewModel::getGetTime)
		);
	}

	@Override
	public XglQRCodePaymentCouponViewModel getInfo(String id) {
		XglQRCodePaymentCouponViewModel byId = this.getById(id);
		if(ObjectUtil.isNull(byId)){
			throw new FailException("券号不存在");
		}
		if(!DateUtil.isIn(new Date(), byId.getStartDate(), byId.getEndDate())){
			throw new FailException("券已过期");
		}
		return byId;
	}
}
